package com.tianchi.lexiang.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.jT.jTHZRecog;
import com.tianchi.lexiang.bean.LeXiangConstants;

public class JniService extends Service {
	private static final String TAG = "JniService";
	public static final String CMD = "cmd";
	public static final String INT_ARRAY = "int_array";

	public static final int INIT = 100;
	public static final int UNKNOWN = INIT - 1;
	public static final int ADD_CHARACTERS = INIT + 1;
	public static final int GET_RECOGNISE = INIT + 2;
	public static final int DESTORY = INIT + 3;

	private jTHZRecog jni = new jTHZRecog();

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int cmd = intent.getIntExtra(CMD, UNKNOWN);
		switch (cmd) {
		case INIT:
			int result = jni.HZInit();
			log("init jni result==>" + result);
			jni.HZSetParam(0, 36);
			jni.HZSetParam(1, 6);
			break;
		case ADD_CHARACTERS:
			Bundle mBundle = intent.getExtras();
			int arrCount = mBundle.getInt(LeXiangConstants.ARRAR_COUNT);
			log("arrCount==>" + arrCount);
			// int[][] characters = new int[arrCount][2];
			short[] characters = new short[arrCount * 2 + 4];
			for (int i = 0; i < arrCount; i++) {
				int[] charater = mBundle
						.getIntArray(LeXiangConstants.ARRAR_INDEX + i);
				for (int j = 0; j < charater.length; j++) {
					log("charater[" + j + "]==>" + charater[j]);
				}
				characters[i * 2] = (short) charater[0];
				characters[i * 2 + 1] = (short) charater[1];
			}
			characters[arrCount * 2] = -1;
			characters[arrCount * 2 + 1] = -1;
			characters[arrCount * 2 + 2] = 0;
			characters[arrCount * 2 + 3] = -1;
			// int res = jni.addCharacters(characters);
			// log("jni.addCharacters  result==>"+res);

			char[] arrayOfChar = new char[73];
			jni.HZRecognize(characters, arrayOfChar);
			String str = new String(arrayOfChar);
			log("str = " + str);
			String[] chars = new String[arrayOfChar.length];
			int length = arrayOfChar.length;
			for (int i = 0; i < length; i++) {
				chars[i] = String.valueOf(arrayOfChar[i]);
			}
			Intent notify = new Intent(LeXiangConstants.RECOGNIZE_HANZI_ACTION);
			notify.putExtra(LeXiangConstants.RECOGNIZE_HANZI, chars);
			sendBroadcast(notify);
			break;
		case GET_RECOGNISE:
			log("GET_RECOGNISE");
			break;
		default:
			break;
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		jni.HZExit();
	}

	private static void log(String msg) {
		Log.d(LeXiangConstants.TAG, "[" + TAG + "]" + msg);
	}
}
